package com.zcah.file.controller;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zcah.common.util.FileUtil;
import com.zcah.common.util.PageUtils;
import com.zcah.common.vo.Query;
import com.zcah.common.vo.R;
import com.zcah.db.domain.ColumnProperty;
import com.zcah.file.dao.FileDao;
import com.zcah.file.domain.FileDO;
import com.zcah.file.service.FileService;

/**
 * 
 * 
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2018-07-06 15:19:12
 */

@RestController
@RequestMapping("/v1/file")
public class FileController {

	private final FileService fileService;
	
	@Autowired
	private FileDao fileDao;

	@Autowired
	public FileController(FileService fileService) {
		this.fileService = fileService;
	}

	@GetMapping("/list")
	// @RequiresPermissions("file:file:file")
	public PageUtils list(@RequestParam Map<String, Object> params) {
		// 查询列表数据
		Query query = new Query(params);
		List<FileDO> fileList = fileService.list(query);
		int total = fileService.count(query);
		PageUtils pageUtils = new PageUtils(fileList, total);
		return pageUtils;
	}

	/**
	 * 保存
	 */
	@PostMapping("/save")
	@RequiresPermissions("file:file:add")
	public R save(@RequestBody FileDO file) {
		if (fileService.save(file) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@RequiresPermissions("file:file:edit")
	public R update(@RequestBody FileDO file) {
		fileService.update(file);
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove/{fileId}")
	@RequiresPermissions("file:file:remove")
	public R remove(@PathVariable Integer fileId) {
		if (fileService.remove(fileId) > 0) {
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@RequiresPermissions("file:file:remove")
	public R remove(@RequestParam("ids[]") Integer[] fileIds) {
		fileService.batchRemove(fileIds);
		return R.ok();
	}

	/**
	 * 验证文件是否存在
	 * 
	 * @param filePath
	 *            文件路径
	 * @return R ok是成功，否则失败
	 */
	@GetMapping("/check")
	public boolean check(String filePath) {
		File file = new File(filePath);
		return file.exists();
	}
	
	@GetMapping("/firstLine/{id}")
	public List<ColumnProperty> getFirstLine(@PathVariable int id, @RequestParam String fileName){
		List<ColumnProperty> columnPropertyList = new ArrayList<>();
		FileDO maskFile = fileDao.get(id);
		File file = new File(maskFile.getFilePath());
		if (file.isDirectory()){
			List<File> fileList = FileUtil.getFileList(file);
			for (File f: fileList){
				if (f.getName().equals(fileName)){
					columnPropertyList.addAll(textFirstLine(f.getAbsolutePath(), maskFile.getFileEncode()
							, maskFile.getTextQualifier()+maskFile.getFileDelimeter()+maskFile.getTextQualifier()));
				}
			}
		}else {
			columnPropertyList.addAll(textFirstLine(file.getAbsolutePath(), maskFile.getFileEncode()
					, maskFile.getTextQualifier()+maskFile.getFileDelimeter()+maskFile.getTextQualifier()));
		}
		return columnPropertyList;
	}

	/**
	 * 文本数据获取第一行数据
	 * @param filePath 文本路径
	 * @param encode 编码格式
	 * @param delimeter 分隔符
	 * @return List<ColumnProperty>
	 */
	private List<ColumnProperty> textFirstLine(String filePath, String encode, String delimeter){
		List<ColumnProperty> columnPropertyList = new ArrayList<>();
		Path path = Paths.get(filePath);
		Charset cs = Charset.forName(encode);
		try {
			Stream<String> lines = Files.lines(path, cs);
			Optional<String> str = lines.findFirst();
			String firstLine;
			if (delimeter.length() == 1){
				firstLine = str.get();
			}else {
				firstLine = str.get().substring(1,str.get().length()-1);
			}
			String[] strArry = firstLine.split(delimeter);
			int i = 0;
			for (String s : strArry) {
				ColumnProperty c = new ColumnProperty();
				c.setId(i++);
				c.setColumnName(s);
				c.setColumnDataType("String");
				c.setColumnComment("-");
				columnPropertyList.add(c);
			}
		} catch (IOException | UncheckedIOException e) {
			e.printStackTrace();
			return null;
		}
		return columnPropertyList;
	}
	
}
